package com.mf.utils;

import com.baomidou.mybatisplus.core.toolkit.LambdaUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;

public class UtilSql {

    /**
     * 构建 JSON_CONTAINS 查询条件
     */
    public static <T> String sqlJsonKey(SFunction<T, ?> sFunction) {
        return "JSON_CONTAINS(" + getColumnName(sFunction) + ", {0})";
    }

    /**
     * 提取数据库字段名（驼峰转下划线）
     */
    private static <T> String getColumnName(SFunction<T, ?> sFunction) {
        String methodName = LambdaUtils.extract(sFunction).getImplMethodName();
        if (methodName.startsWith("get")) {
            methodName = methodName.substring(3);
        } else if (methodName.startsWith("is")) {
            methodName = methodName.substring(2);
        }
        return toUnderlineCase(methodName); // 如 getRoleList → role_list
    }

    /**
     * 驼峰转下划线
     */
    private static String toUnderlineCase(String camelCase) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < camelCase.length(); i++) {
            char ch = camelCase.charAt(i);
            if (Character.isUpperCase(ch)) {
                if (i > 0) {
                    result.append("_");
                }
                result.append(Character.toLowerCase(ch));
            } else {
                result.append(ch);
            }
        }
        return result.toString();
    }

    /**
     * 构建 JSON 字符串值（用于字符串数组）
     */
    public static String sqlJsonValue(Object value) {
        return "\"" + value + "\"";
    }
}
